import { getToken, setToken, removeToken } from "@/utils/auth"
import { login, getUserProfile, getUserDetailById, logout } from "@/api/user"
import { resetRouter } from "@/router"
// 暴露仓库的实例对象
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    //更新token
    updateToken(state, token) {
      state.token = token
      //进行token的持久化
      setToken(token)
    },
    //删除token
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    //更新用户信息
    updateUserInfo(state, info) {
      state.userInfo = info
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async userLogin(context, loginForm) {

      const res = await login(loginForm)
      console.log('2');
      // 将token存到vuex中
      context.commit('updateToken', res.data)
    },
    //获取用户信息，发送请求
    async getUserInfo(context) {
      try {
        const res = await getUserProfile()
        console.log('res', res);

        const info = await getUserDetailById(res.data.userId)

        // 获取用户信息res.data存储到vuex
        context.commit('updateUserInfo', { ...res.data, ...info.data })

        // 返回页面的权限信息
        return res.data.roles.menus
      } catch (error) {
        console.log('error', error);
      }
    },
    //清空信息
    logout(context) {
      context.commit('removeToken')
      context.commit('removeUserInfo')
      resetRouter()//重置路由
    }
  }
}

